package com.navercorp.utilset.input;

import ohos.accessibility.AccessibilityEventInfo;
import ohos.accessibility.ability.AccessibleAbility;
import ohos.app.Context;

import java.util.Timer;
import java.util.TimerTask;

/**
 *
 * @author jaemin.woo
 *
 */
public class KeyboardUtils {
    private static SoftwareKeyDetector deviceKeyboardDetector;

    private static AccessibleAbility accessibleAbility;

    static {
        deviceKeyboardDetector = new SoftwareKeyDetector();
        accessibleAbility = new AccessibleAbility() {
            @Override
            public void onAccessibilityEvent(AccessibilityEventInfo accessibilityEventInfo) {
            }

            @Override
            public void onInterrupt() {
            }
        };
    }

    private KeyboardUtils() {
        /* Do nothing */
    }

    /**
     * Shows keypad
     */
    public static void showSoftKeyboard() {
        accessibleAbility.getSoftKeyBoardController().setShowMode(AccessibleAbility.SHOW_MODE_AUTO);
    }

    /**
     * Hides keypad
     */
    public static void hideSoftKeyboard() {
        accessibleAbility.getSoftKeyBoardController().setShowMode(AccessibleAbility.SHOW_MODE_HIDE);
    }

    /**
     * Toggles keypad
     */
    public static void toggleKeyPad() {
        int mode = accessibleAbility.getSoftKeyBoardController().getShowMode();
        int newMode = (mode == AccessibleAbility.SHOW_MODE_HIDE)
            ? AccessibleAbility.SHOW_MODE_AUTO
            : AccessibleAbility.SHOW_MODE_HIDE;
        accessibleAbility.getSoftKeyBoardController().setShowMode(newMode);
    }

    /**
     * Delayed version of {@link #hideSoftKeyboard()
     * hideSoftKeyboard} method
     *
     * @param delay int
     */
    public static void delayedHideSoftKeyboard(int delay) {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                hideSoftKeyboard();
            }
        };

        Timer timer = new Timer();
        timer.schedule(task, delay);
    }

    /**
     * Delayed version of {@link #showSoftKeyboard()
     * showSoftKeyboard} method
     *
     * @param delay int
     */
    public static void delayedShowSoftKeyboard(int delay) {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                showSoftKeyboard();
            }
        };

        Timer timer = new Timer();
        timer.schedule(task, delay);
    }

    /**
     * Determines if the device has software keys.
     *
     * @param context Context
     * @return true if device has software keys; false otherwise
     */
    public static boolean hasSoftwareKeys(Context context) {
        return deviceKeyboardDetector.hasSoftwareKeys(context);
    }
}
